<template>
	<div class="color-svpanel" :style="{
		backgroundColor: background
	}">
		<div class="color-svpanel__white"></div>
		<div class="color-svpanel__black"></div>
		<div class="color-svpanel__cursor" :style="{
			top: cursorTop + 'px',
			left: cursorLeft + 'px'
		}">
			<div></div>
		</div>
	</div>
</template>

<script setup lang="ts">
import draggable from '../util/draggable'
import { SvPanelProps } from "../color-picker";
const props = defineProps(SvPanelProps);
const instance = getCurrentInstance()
const cursorTop = ref(0) //管理光标(上)
const cursorLeft = ref(0) //管理光标(左)
const background = ref('hsl(0, 100%, 50%)')

/**
 * 计算颜色值
 */
const colorValue = computed(() => {
	const hue = props.color?.get('hue')
	const value = props.color?.get('value')
	return { hue, value }
})

/**
 * 监听颜色值
 */
watch(
	() => colorValue.value,
	() => {
		update()
	}
)

/**
 * update更新事件
 */
const update = () => {
	const saturation = props.color?.get('saturation')
	const value = props.color?.get('value')
	const ele = instance?.vnode.el as HTMLElement
	cursorLeft.value = (saturation * ele.clientWidth) / 100
	cursorTop.value = ((100 - value) * ele.clientHeight) / 100
	background.value = `hsl(${props.color?.get('hue')}, 100%, 50%)`
}

/**
 * handleDrag拖拽事件
 * @param event
 */
const handleDrag = (event: any) => {
	const ele = instance?.vnode.el as HTMLElement
	const rect = ele.getBoundingClientRect()

	let left = event.clientX - rect.left
	let top = event.clientY - rect.top

	left = Math.max(0, left)
	left = Math.min(left, rect.width)
	top = Math.max(0, top)
	top = Math.min(top, rect.height)

	cursorLeft.value = left
	cursorTop.value = top

	props.color?.set({
		saturation: (left / rect.width) * 100,
		value: 100 - (top / rect.height) * 100
	})
}
defineExpose({ update });
onMounted(() => {
	update()
	const ele = instance?.vnode.el as HTMLElement
	draggable(ele, {
		drag: (event: any) => {
			handleDrag(event)
		},
		end: (event: any) => {
			handleDrag(event)
		}
	})
})
</script>
